using System;
using System.Web.UI.WebControls;
using Sedna.Core.Common.Objects.Navigation;
using Sedna.Core.Controller;

namespace Sedna.Core.Controls.Grid
{
	/// <summary>
	/// Summary description for GridDatePicker.
	/// </summary>
	public class GridDatePicker: DatePicker, IDataGridAwareControl
	{
		private IDataGridController controller;

		public IDataGridController Controller
		{
			set { controller = value; }
		}

		public GridDatePicker(IConfiguration configuration) : base(configuration)
		{
			this.TextChanged+=new EventHandler(OnTextChanged);
		}

		private void OnTextChanged(object sender, EventArgs e)
		{
			UpdateEntity();
		}

		private void UpdateEntity()
		{
            object entity = this.controller.GridSourceCache[(int)ViewState["entityIndex"]];

			if (binder.Unbind(entity, "Value", configuration.DataParser)|binder.Unbind(entity, "Text", configuration.DataParser))
			{
                controller.TransientData.Remove(entity);
                controller.TransientData.Add(entity);
            }
			
		}


		public void OnDataBinding(DataGridItem dataGridItem)
		{
            ViewState["entityIndex"] = dataGridItem.DataSetIndex;
            binder.Bind(dataGridItem.DataItem, new string[] { "Value", "Enabled" });
		}


		protected override void Bind() 
		{
		}

		protected override void Unbind()
		{
		}

        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            if (controller.InvalidData.Contains(this.controller.GridSourceCache[(int)ViewState["entityIndex"]]))
                this.textBox.CssClass = "invalidinput";
            base.Render(writer);
        }
	}
}
